package com.meicloud.license.appl.service.impl;

import cn.hutool.core.map.MapUtil;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA签名模式工具类
 *
 * @author zhanghui145
 * @date 2022/1/11 9:57
 * @since 1.0.0
 */
@Component
public class RsaUtils extends AbstractEncryptionUtils<String> {

    @Override
    public String encrypt(String plaintext, String rule) {
        try {
            //取得私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
                    Base64.getDecoder().decode(rule.getBytes(StandardCharsets.UTF_8)));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            //生成私钥
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            //数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return new String(Base64.getEncoder().encode(
                    cipher.doFinal(plaintext.getBytes())), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String decrypt(String decoderStr, String rule) {
        try{
            //实例化密钥工厂
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            //初始化公钥
            //密钥材料转换
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(
                    Base64.getDecoder().decode(rule.getBytes(StandardCharsets.UTF_8)));
            //产生公钥
            PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
            //数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, pubKey);
            byte[] decoderByte = Base64.getDecoder().decode(decoderStr.getBytes(StandardCharsets.UTF_8));
            return new String(cipher.doFinal(decoderByte), StandardCharsets.UTF_8);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public Map<String, String> getKeyPairGenerator() {
        try {
            // 密钥长度必须是64的倍数，在512到65536位之间
            final int keySize = 1024;
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            // 初始化KeyPairGenerator对象,密钥长度
            kpg.initialize(keySize);
            // 生成密匙对
            KeyPair keyPair = kpg.generateKeyPair();
            // 得到公钥
            Key publicKey = keyPair.getPublic();
            String publicKeyStr = new String(
                    Base64.getEncoder().encode(publicKey.getEncoded()), StandardCharsets.UTF_8);
            // 得到私钥
            Key privateKey = keyPair.getPrivate();
            String privateKeyStr = new String(
                    Base64.getEncoder().encode(privateKey.getEncoded()), StandardCharsets.UTF_8);
            // map装载公钥和私钥
            Map<String, String> keyPairMap = new HashMap<>();
            keyPairMap.put("publicKey", publicKeyStr);
            keyPairMap.put("privateKey", privateKeyStr);
            return keyPairMap;
        } catch (Exception e) {
            e.printStackTrace();
            return MapUtil.empty();
        }
    }
}
